package merge_string

import (
	"strings"
)

func CreateByteSlice(s1, s2 string) (*[]byte, *[]byte) { //字节切片生成函数，返回字符串生成的字节切片指针
	s1l := make([]byte, 0, len(s1))
	s2l := make([]byte, 0, len(s2))
	for i := 0; i < len(s1); i++ {
		s1l = append(s1l, s1[i])
	}
	for j := 0; j < len(s2); j++ {
		s2l = append(s2l, s2[j])
	}
	return &s1l, &s2l
}

func MergeString(bs1, bs2 *[]byte) string { //合并函数，传入指针
	bs1l := len(*bs1)
	bs2l := len(*bs2)
	msl := bs1l + bs2l
	ms := make([]byte, msl) //生成固定的底层数组，减少底层数组复制
	var b strings.Builder
	if bs1l == bs2l {
		for i := 0; i < bs1l; i++ { //两段字节切片相同长度的情况
			ms[2*i] = (*bs1)[i]
			ms[2*i+1] = (*bs2)[i]
		}
	} else if bs1l < bs2l { //前一个字节切片比后一个字节切片长度小的情况
		for i := 0; i < bs1l; i++ {
			ms[2*i] = (*bs1)[i]
			ms[2*i+1] = (*bs2)[i]
		}
		for j := 0; j < bs2l-bs1l; j++ { //超出部分用长切片剩余部分替换，ms的底层数组地址不变
			ms[2*bs1l+j] = (*bs2)[bs1l+j]
		}
	} else if bs1l > bs2l { //前一个字节切片比后一个字节切片长度大的情况
		for i := 0; i < bs2l; i++ {
			ms[2*i] = (*bs1)[i]
			ms[2*i+1] = (*bs2)[i]
		}
		for j := 0; j < bs1l-bs2l; j++ { //超出部分用长切片剩余部分替换，ms的底层数组地址不变
			ms[2*bs2l+j] = (*bs1)[bs2l+j]
		}
	}
	b.Write(ms)       //字节切片拼接字符串
	return b.String() //返回拼接后的字符串
}
